import { Component, Inject, Injector, OnInit, SkipSelf, ViewChild, ChangeDetectionStrategy, ChangeDetectorRef, inject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ErrorStateMatcher } from '@angular/material/core';
import { MAT_DIALOG_DATA, MatDialogRef, MatDialogModule } from '@angular/material/dialog';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { FormControl, FormGroup, FormGroupDirective, NgForm, ReactiveFormsModule } from '@angular/forms';
import { TranslatePipe } from '@ngx-translate/core';
import { BaseData } from '@shared/models/base-data';
import { AnchorComponent } from '@shared/components/anchor.component';
import { DialogComponent } from '@shared/components/dialog.component';
import { TableConfig } from '@shared/models/table/table-config.models';
import { ItemComponent } from './item.component';
import { ItemAddDialogData } from '@shared/models/table/table-data.models';

/**
 * 新增数据对话框组件
 * 
 * 功能特性：
 * - 支持动态加载表单组件
 * - 自动表单验证
 * - 集成加载状态管理
 * - 符合 Angular Material MDC 规范
 */
@Component({
  selector: 'cne-item-add-dialog',
  standalone: true,
  imports: [
    CommonModule,
    ReactiveFormsModule,
    MatDialogModule,
    MatButtonModule,
    MatIconModule,
    MatToolbarModule,
    MatProgressBarModule,
    AnchorComponent,
    TranslatePipe
  ],
  providers: [{ provide: ErrorStateMatcher, useExisting: ItemAddDialogComponent }],
  changeDetection: ChangeDetectionStrategy.OnPush,
  templateUrl: './item-add-dialog.component.html',
  styleUrls: ['./item-add-dialog.component.scss']
})
export class ItemAddDialogComponent extends
  DialogComponent<ItemAddDialogComponent, BaseData> implements OnInit, ErrorStateMatcher {

  itemComponent: ItemComponent<BaseData> | null = null;

  // 表单组（用于验证）
  detailsForm: FormGroup;

  // 表格配置
  readonly tableConfig: TableConfig<BaseData>;

  // 对话框标题
  readonly title: string = 'action.add';

  item: BaseData;

  // 提交状态
  submitted = false;

  // 锚点组件引用（用于动态加载表单组件）
  @ViewChild('itemDetailsFormAnchor', { static: true }) itemDetailsFormAnchor!: AnchorComponent;

  // 依赖注入
  private readonly injector = inject(Injector);
  private readonly cd = inject(ChangeDetectorRef);

  constructor(
    public override dialogRef: MatDialogRef<ItemAddDialogComponent, BaseData>,
    @Inject(MAT_DIALOG_DATA) public data: ItemAddDialogData<BaseData>,
    @SkipSelf() private readonly parentErrorStateMatcher: ErrorStateMatcher
  ) {
    super(dialogRef);
    this.tableConfig = data.tableConfig;
    this.item = {};
  }

  ngOnInit(): void {
    // 如果配置了表单组件，动态加载它
    if (this.tableConfig.itemComponent) {
      this.loadFormComponent();
    } else {
      // 如果没有表单组件，创建一个基本的表单
      this.detailsForm = new FormGroup({});
    }
  }

  /**
   * 动态加载表单组件
   */
  private loadFormComponent(): void {
    const viewContainerRef = this.itemDetailsFormAnchor.viewContainerRef;
    viewContainerRef.clear();

    // 创建注入器，提供必要的依赖
    const injector = Injector.create({
      providers: [
        {
          provide: 'tableConfig',
          useValue: this.tableConfig
        },
        {
          provide: 'item',
          useValue: this.item
        }
      ],
      parent: this.injector
    });

    // 动态创建组件实例
    const componentRef = viewContainerRef.createComponent(
      this.tableConfig.itemComponent,
      { index: 0, injector }
    );

    this.itemComponent = componentRef.instance;
    this.itemComponent.isEdit = true;
    this.detailsForm = this.itemComponent.itemForm;
  }

  /**
   * 错误状态匹配（实现 ErrorStateMatcher 接口）
   */
  isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
    const originalErrorState = this.parentErrorStateMatcher.isErrorState(control, form);
    const customErrorState = !!(control && control.invalid && this.submitted);
    return originalErrorState || customErrorState;
  }

  /**
   * 取消操作
   */
  cancel(): void {
    this.dialogRef.close(null);
  }

  /**
   * 确认添加
   */
  add(): void {
    this.submitted = true;
    
    if (this.detailsForm.valid) {
      this.item = {...this.item, ...this.itemComponent.itemFormValue()};
      this.tableConfig.saveItem(this.item).subscribe(
        (item) => {
          this.dialogRef.close(item);
        }
      );
    }
  }
}
